<template>
  <div></div>
</template>

<script setup lang="ts" name="SocialCallback">
import { LoginData } from "@/views/login/types";
import { setToken } from "@/utils/auth";
import { nextTick, onMounted } from "vue";
import { login } from "@/api/login";
import { authBinding } from "@/views/login/fetchData";
import { closeToast, showLoadingToast } from "vant";

const source = "wechat_enterprise";
const tenantId = "918893";

const processResponse = async (res: any) => {
  if (res.code !== 200) {
    throw new Error(res.msg);
  }
  if (res.data !== null) {
    setToken(res.data.access_token);
  }
  // showToast(res.msg);
  setTimeout(() => {
    closeToast();
    location.href = import.meta.env.VITE_PUBLIC_PATH + "#/home";
  }, 200);
};

const handleError = () => {
  // showFailToast(error.message);
  setTimeout(() => {
    location.href = import.meta.env.VITE_PUBLIC_PATH + "#/login";
  }, 200);
};

const loginByCode = async (data: LoginData) => {
  try {
    const res = await login(data);
    await processResponse(res);
  } catch (error) {
    handleError();
  }
};
const getUrlParams = () => {
  const obj = {};
  const str = location.search || "";

  if (str && str.slice(1)) {
    // 去掉 ？ ，然后以 & 分割
    let queryArray = str.slice(1).split("&");
    queryArray.map(query => {
      // param=value 以 = 分割
      let temp = query.split("=");
      if (temp.length > 1) {
        // 收集参数
        obj[temp[0]] = temp[1];
      }
    });
  }
  return obj;
};

const getState = async () => {
  const res: any = await authBinding(
    source,
    tenantId,
    "exshow-web.cbebaiwen.com"
  );
  const index = res.data.indexOf("state=");
  return res.data.slice(index + 6);
};

const init = async () => {
  showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    overlay: true,
    message: "登录中..."
  });
  const state = await getState();
  const params = getUrlParams() as { code: string; state: string };
  const data: LoginData = {
    socialCode: params.code,
    socialState: state,
    tenantId: tenantId,
    source: source,
    clientId: "a79512f8a328d32329e3505a90f33ddf",
    grantType: "social"
  };
  await loginByCode(data);
};

onMounted(() => {
  nextTick(() => {
    init();
  });
});
</script>

<style scoped lang="less"></style>
